package com.zjitc.controller;

import com.zjitc.common.Gsonal;
import com.zjitc.common.ServerResponse;
import com.zjitc.pojo.express.KdniaoTrackQueryAPI;
import com.zjitc.pojo.*;
import com.zjitc.pojo.exp.DemoExpress;
import com.zjitc.pojo.exp.ExpResult;
import com.zjitc.service.*;
import com.zjitc.utils.old.Utils;
import com.zjitc.vo.PageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * Create By IntelliJ IDEA
 *
 * @author: myq
 * @create-Time: 2017/11/23  11:47
 */
@Controller
@RequestMapping("/order")
public class OrderController extends BaseController {

  @Autowired
  private OrderService service;
  @Autowired
  private CarService carService;
  @Autowired
  private ProductService pservice;
  @Autowired
  private UserService userService;
  @Autowired
  private ExpressService expressService;
  private final String USER = "user";
  private final String PAGE = "page";
  private final String ORDER = "order";
  private final String TOTAL_AMOUNT = "total_amount";
  private final String OUT_TRADE_NO = "out_trade_no";

  private static final String PAY = "pay";
  private static final String REFUND = "refund";
  private static final String KDDH = "3897420168186";

  /**
   * 商品结算 添加至订单操作
   */
  @RequestMapping(value = "/addOrder",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse addorder(String aid,Float total,HttpSession session)
      throws ServletException, IOException, InterruptedException {
    User user = getSessionUser(session);
    List<Caritem> carItems = carService.findAll(user.getUid());
    return service.addorder(aid,total,user, carItems);
  }

  /**
   * 订单列表
   */
  @RequestMapping("/orderlist")
  public ModelAndView list(HttpSession session,
                           @RequestParam(value = "pageid", required = false, defaultValue = "0") Integer pageid)
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    User user = getSessionUser(session);
    PageModel<Orders> orders = service.findPageByUid(user.getUid(), pageid);
    modelAndView.addObject(PAGE, orders);
    modelAndView.setViewName("order/order_list");
    return modelAndView;
  }

  /**
   * 立即购买的处理逻辑
   */
  @RequestMapping("/orderPay")
  public ModelAndView orderpay(String oid, HttpSession session)
      throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    User user = getSessionUser(session);
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    modelAndView.addObject(ORDER, order);
    modelAndView.setViewName("order/order_info");
    return modelAndView;
  }


  @RequestMapping("/gotoOrderInfo")
  public ModelAndView gotoOrderInfo(HttpSession session) {
    ModelAndView m = new ModelAndView("order/order_info");
    Orders orders = (Orders) session.getAttribute(ORDER);
    m.addObject("order", orders);
    return m;
  }

  @RequestMapping("/checkOutSuccess")
  public ModelAndView goOutSuccess(String oid, String option, String invoice, HttpSession session){
    User user = getSessionUser(session);
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    String phone = Utils.confident(order.getPhone());
    order.setPhone(phone);
    ModelAndView mv = new ModelAndView("order/checkOutSuccess");
    mv.addObject("order",order);
    mv.addObject("option",option);
    mv.addObject("invoince",invoice);
    return mv;
  }

  /**
   * 点击下一步之后前往支付
   */
  @RequestMapping("/CompleteOrder")
  public ModelAndView complete(
          String oid ,String total, HttpSession session)
      throws ServletException, IOException, SQLException {
    User user = getSessionUser(session);
    ModelAndView modelAndView = new ModelAndView("alipay.trade.page.pay");
    if(user == null){
      modelAndView.setViewName("user/login");
      return modelAndView;
    }
    boolean b = service.checkOrder(oid,user.getUid());
    //总价
    modelAndView.addObject(TOTAL_AMOUNT, total);
    //订单编号
    modelAndView.addObject(OUT_TRADE_NO, oid);
    //alipay.trade.page.pay.jsp    outTradeNo    totalAmount
    return modelAndView;
  }

  /**
   * 支付完成后跳转显示
   */
  @RequestMapping("/completePay")
  public ModelAndView completepay(
      @RequestParam("out_trade_no") String oid,
      @RequestParam("trade_no") String tradeNo,
      HttpSession session
  ) throws SQLException, IOException {
    User user = getSessionUser(session);
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    order.setState("1");
    Integer integral = (int) (order.getTotalPrice() * 0.01);
    user.setIntegral(user.getIntegral() + integral);
    userService.updateIntegral(user.getIntegral(),user.getUid());
    order.getOrderitems().forEach(orderitem ->{
      Product product = pservice.findbyid(orderitem.getPid());
      product.setMonthlySales(product.getMonthlySales() + orderitem.getCount());
      pservice.updateProduct(product);
    });
    //修改orders数据库
    service.update(user, order);
    service.updateinventory(order.getOrderitems(),PAY);
    ModelAndView m = new ModelAndView();
    m.addObject("total",order.getTotalPrice());
    m.setViewName("redirect:/order/orderSuccess.do");
    return m;
  }

  @RequestMapping("/orderSuccess")
  public ModelAndView ordersuccess(Float total){
    ModelAndView mv = new ModelAndView("order/PaySuccess");
    mv.addObject("total",total);
    return mv;
  }

  /**
   * 删除订单
   */
  @RequestMapping(value = "/orderDelete",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse delete(String oid, HttpSession session)
      throws ServletException, IOException {
    User user = getSessionUser(session);
    return service.deleteorder(user.getUid(), oid);
  }

  @RequestMapping("/orderDeleteAll")
  public String deleteall(HttpSession session) {
    User user = getSessionUser(session);
    int i = service.deleteAllorder(user.getUid());
    return "redirect:/order/orderlist.do";
  }


  /**
   * 查快递
   * @param oid
   * @param session
   * @return
   * @throws Exception
   */
  @RequestMapping("expcheck")
  @ResponseBody
  public Object expcheck(String oid, HttpSession session) throws Exception {
    User user = getSessionUser(session);
    Orders order = service.findOrderFromRedis(user.getUid(), oid);
    //快递即时查询
    KdniaoTrackQueryAPI kdn = new KdniaoTrackQueryAPI();
    String result = kdn.getOrderTracesByJson("YD", KDDH);
    ExpResult expResult = Gsonal.fromJson(result, ExpResult.class);
    ExpResult overwrite = DemoExpress.overwrite(expResult, order);
      return overwrite;
  }

  @RequestMapping("confirm")
  public String confirm(String oid, HttpSession session) {
    User user = getSessionUser(session);
    service.confirm(user, oid);
    return "redirect:/order/orderlist.do";
  }


/**  取消订单/退款  */
  @RequestMapping("/orderCancel")
  public ModelAndView cancel(
          @RequestParam(value = "oid") String outTradeNo,
          @RequestParam(value = "total") String refundAmount,
          @RequestParam("cause") String refundReason
  ) throws ServletException, IOException {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject("oid", outTradeNo);
    modelAndView.addObject("total", refundAmount);
    modelAndView.addObject("reason", refundReason);
    modelAndView.setViewName("alipay.trade.refund");
    return modelAndView;
  }

  @RequestMapping("/refund")
  public ModelAndView refund(
          String msg, @RequestParam("oid") String oid, HttpSession session)
      throws SQLException, ServletException, IOException {
    User user = getSessionUser(session);
    String msg2 = "";
    String success = "Success";
    if (success.equals(msg)) {
      Orders order = service.findOrderFromRedis(user.getUid(), oid);
      order.setState("4");
      service.update(user, order);
      service.updateinventory(order.getOrderitems(),REFUND);
      msg = "您已成功退款";
      msg2 = "系统会在一个小时内将金额退回银行卡，请您注意信息提示";
    } else {
      msg = "您发起的退款失败咯";
      msg2 = "请您仔细检查订单信息后再发起吧";
    }
    ModelAndView modelAndView = new ModelAndView("order/refundSuccess");
    modelAndView.addObject("msg", msg);
    modelAndView.addObject("msg2", msg2);
    return modelAndView;
  }

}
